import { Injectable } from '@nestjs/common';
import { User, UserDocument } from '@app/database/schemas/user.schema';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { UserDto } from './dto/login.dto';
import { compareSync } from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(
    @InjectModel('User')
    private readonly userModel: Model<UserDocument>,
    private readonly jwtService: JwtService,
  ) {}

  async validateUser(
    username: string,
    password: string,
  ): Promise<UserDocument> {
    const user = await this.userModel.findOne({ username }).select('+password');
    if (user && compareSync(password, user.password)) {
      delete user.password;
      return user;
    }
    return null;
  }

  login(userDto: UserDto) {
    const payload = { _id: userDto._id };
    return {
      token: this.jwtService.sign(payload),
    };
  }

  register(user: User) {
    user.grant = 0;
    return this.userModel.create(user);
  }
}
